import asyncio
import sys
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool
from adb.client import ADBClient


# 创建服务器实例
server = Server("adb-mcp-server")
adb_client = ADBClient()


@server.list_tools()
async def list_tools():
    """列出可用的工具"""
    return [
        Tool(
            name="list_devices",
            description="列出连接的Android设备",
            inputSchema={
                "type": "object",
                "properties": {},
                "required": []
            }
        ),
        Tool(
            name="get_device_info",
            description="获取指定设备的详细信息",
            inputSchema={
                "type": "object",
                "properties": {
                    "device_id": {
                        "type": "string",
                        "description": "设备ID"
                    }
                },
                "required": ["device_id"]
            }
        ),
        Tool(
            name="check_device_status",
            description="检查设备连接状态",
            inputSchema={
                "type": "object",
                "properties": {
                    "device_id": {
                        "type": "string",
                        "description": "设备ID"
                    }
                },
                "required": ["device_id"]
            }
        )
    ]


@server.call_tool()
async def call_tool(name: str, arguments: dict):
    """调用工具"""
    if name == "list_devices":
        try:
            devices = adb_client.list_devices()
            result_text = f"找到 {len(devices)} 个设备:\n"
            for device in devices:
                result_text += f"- {device.device_id} ({device.status})\n"
                if device.product:
                    result_text += f"  产品: {device.product}\n"
                if device.model:
                    result_text += f"  型号: {device.model}\n"
            
            return [TextContent(type="text", text=result_text)]
        except Exception as e:
            return [TextContent(type="text", text=f"获取设备列表失败: {str(e)}")]
    
    elif name == "get_device_info":
        device_id = arguments.get("device_id")
        if not device_id:
            return [TextContent(type="text", text="错误: device_id参数是必需的")]
        
        try:
            info = adb_client.get_device_info(device_id)
            info_text = f"设备 {device_id} 的详细信息:\n"
            for key, value in info.items():
                if key == 'properties':
                    info_text += f"- {key}: [系统属性]\n"
                else:
                    info_text += f"- {key}: {value}\n"
            
            return [TextContent(type="text", text=info_text)]
        except Exception as e:
            return [TextContent(type="text", text=f"获取设备信息失败: {str(e)}")]
    
    elif name == "check_device_status":
        device_id = arguments.get("device_id")
        if not device_id:
            return [TextContent(type="text", text="错误: device_id参数是必需的")]
        
        try:
            is_online = adb_client.check_device_status(device_id)
            status = "在线" if is_online else "离线"
            return [TextContent(type="text", text=f"设备 {device_id} 状态: {status}")]
        except Exception as e:
            return [TextContent(type="text", text=f"检查设备状态失败: {str(e)}")]
    
    else:
        return [TextContent(type="text", text=f"未知的工具: {name}")]


async def main():
    """主函数"""
    async with stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            server.create_initialization_options()
        )


if __name__ == "__main__":
    asyncio.run(main())